import pkg from 'glob'
import fs from 'fs'
import { loadEnv } from 'vite'
import { resolve } from 'path'
import pageConfig from './src/pageConfig'

const { glob } = pkg

export const rollupInput = (env) => {
  // 读取全部的main文件路径
  const allEntry = glob.sync('./src/pages/**/main.js')
  // 读取html模版信息
  const temp = fs
    .readFileSync(resolve(__dirname, './src/template.html'))
    .toString()
  // 初始化入口文件配置
  const entryPage = {}
  // 初始化模版文件内容
  let content = ''
  allEntry.forEach((entry) => {
    const pageName = entry.split('/')[3]
    const pageTitle = pageConfig[pageName].title
    const pageSrc = entry.replace('src/', '')
    const mode = {
      title: pageTitle, // 页面标题
      name: pageName, // 页面名字
      src: pageSrc // main.ts路径
    }
    const writeHtmlPath = resolve(__dirname, `./src/${mode.name}.html`)

    entryPage[mode.name] = writeHtmlPath
    content = temp.replace(/{{(.*?)}}/gi, (match, p1) => {
      const p = p1.trim()
      if (p.indexOf('VITE_ENV') >= 0) { // 根据打包环境区分是否加载js
        if (loadEnv(env, resolve(__dirname, './src'))[p] === '1') {
          return loadEnv(env, resolve(__dirname, './src'))[p + '_URL']
        } else {
          return ''
        }
      } else if (p.indexOf('VITE_PAGE') >= 0) { // 根据具体的页面业务区分是否加载js
        if (pageConfig[pageName][p]) {
          return loadEnv(env, resolve(__dirname, './src'))[p + '_URL']
        } else {
          return ''
        }
      } else { // 替换页面的普通变量
        return mode[p1.trim()]
      }
    })

    // 写入口文件
    fs.writeFileSync(writeHtmlPath, content)
  })

  return entryPage
}
